package cn.iune.erp.inventory;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

@Transactional
@Service
public class StocktakingServiceImpl implements IStocktakingService {
	private final Logger log = LogManager.getLogger(this);

	@Autowired
	private IStocktakingDao dao;
	@Autowired
	private IStocktakingDetailDao detailDao;
	

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#getAll()
	 */
	@Override
	public List<Stocktaking> getAll(){
		return dao.getAll();
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#getByID(java.lang.String)
	 */
	@Override
	public Stocktaking getByID(String fID) {
		return dao.getByID(fID);
	}
	
	@Transactional
	@Override
	public void insert(Stocktaking obj) {
		dao.insert(obj);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#delete(java.lang.String)
	 */
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}

	@Transactional
	@Override
	public void update(Stocktaking obj) {
		dao.update(obj);
	}

	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#getByNo(java.lang.String, java.lang.String)
	 */
	@Override
	public Stocktaking getByNo(String documentNo, String enterpriseNo) {
		return dao.getByNo(documentNo, enterpriseNo);
	}

	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException {
		//System.out.println("Stocktaking.save-->"+object.toJSONString());
		/*
		//判断数据（日期型数据是否合格）
		String relationAlias = object.getJSONObject("userdata").getString("relationAlias");
		String relationTypes = object.getJSONObject("userdata").getString("relationTypes");
		System.out.println("Stocktaking.save.relationAlias-->"+relationAlias);
		System.out.println("Stocktaking.save.relationTypes-->"+relationTypes);
		
		String[] cols = relationAlias.split(",");
		String[] types = relationTypes.split(",");
		
		JSONArray data = object.getJSONArray("rows");
		//循环行
		System.out.println("**********行数"+data.size());
		for(int index=0;index<data.size();index++) {
			JSONObject row = data.getJSONObject(index);
			System.out.println("**********"+row.toJSONString());
			//循环列
			for(int i=0;i<cols.length;i++) {
				String type = types[i];
				if("Date".equals(type) || "DateTime".equals(type)) {
					String col = cols[i];
					JSONObject cvalue = row.getJSONObject(col);
					System.out.println("type-->>"+type+"-->>column-->>"+col+"-->>value-->>"+cvalue.get("value"));
					System.out.println("type-->>"+type+"-->>column-->>"+col+"-->>value-->>"+cvalue.get("originalValue"));
				}
			}
		}
		*/
		
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", "Stocktaking");
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			Stocktaking obj = JSON.toJavaObject(javaObject, Stocktaking.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				Stocktaking objNew = dao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
	}
	
	@Transactional
	@Override
	public JSONObject saveDetail(JSONObject object) throws ParseException {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", "StocktakingDetail");
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			StocktakingDetail obj = JSON.toJavaObject(javaObject, StocktakingDetail.class);
			if(RowState.NEW.equals(obj.getRowState())){
				detailDao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				detailDao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				StocktakingDetail data = detailDao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", data.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
	}

	
	
	
	///////////////////////业务功能///////////////////////////////////////
	
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#confirm(java.lang.String)
	 */
	@Transactional
	@Override
	public int confirm(String fID) {
		Stocktaking sr = dao.getByID(fID);
		sr.setState("confirm");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#active(java.lang.String)
	 */
	@Transactional
	@Override
	public int active(String fID) {
		Stocktaking sr = dao.getByID(fID);
		sr.setState("active");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#close(java.lang.String)
	 */
	@Transactional
	@Override
	public int close(String fID) {
		Stocktaking sr = dao.getByID(fID);
		sr.setStatus("close");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#open(java.lang.String)
	 */
	@Transactional
	@Override
	public int open(String fID) {
		Stocktaking sr = dao.getByID(fID);
		sr.setStatus("open");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#agreeIt(java.lang.String)
	 */
	@Transactional
	@Override
	public int agreeIt(String fID,String usercode,String username, String userId) {
		Stocktaking sr = dao.getByID(fID);
//		System.out.println("fID-->"+fID);
//		System.out.println("sr-->"+sr);

		sr.setAudit("confirm");
		sr.setConfirmDate(Utils.getCurrentDate());
		
		sr.settUsercode(usercode);
		sr.settUsername(username);
		sr.settDatetime(Utils.getCurrentDateTime());

		dao.update(sr);

		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStocktakingService#unAgree(java.lang.String)
	 */
	@Transactional
	@Override
	public int unAgree(String fID) {
		Stocktaking sr = dao.getByID(fID);
		//判断是否可以撤销
		
		sr.setAudit("active");
		sr.setConfirmDate(null);
		
		sr.settUsercode(null);
		sr.settUsername(null);
		sr.settDatetime(null);

		dao.update(sr);

		return 0;
	}

	
	
	
	@Override
	public Stocktaking packing(
			String billType
			,String billTypeName 
			,String systemCode 

			,String cUsercode//=com.justep.system.context.ContextHelper.getOperator().getCode();
			,String cUsername//=com.justep.system.context.ContextHelper.getOperator().getName();
			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		
		String APPID = null;

		Stocktaking obj = new Stocktaking();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		
		obj.setBillType(billType);
		obj.setBillTypeName(billTypeName);
		obj.setSystemCode(APPID);
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setAudit("active");
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
		
		obj.setDetailsCount(0);
		obj.setDetailsCountState(0);
		obj.setMaxDetailNo(0);
		
		obj.setVersion(0);
		
		return obj;
	}
	
	
	
	
	@Override
	public JSONObject newData(JSONObject param) {
		return dao.create(param);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
//		String ucode = param.getString("ucode");
//		String uname = param.getString("uname");
//		String uid = param.getString("uid");
		
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			//首先删除子表
			List<StocktakingDetail> srds = detailDao.getByMasterID(id);
			for(StocktakingDetail srd:srds){
				detailDao.delete(srd.getfID());
			}

			//然后删除主表
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}
	
	@Override
	public JSONObject saveData(JSONObject param) {
		// TODO Auto-generated method stub
		JSONObject data;
		try {
			//保存主表
			data = this.save(param);
			
			//保存从表
			JSONArray slaves = param.getJSONArray("slaves");
			JSONObject slaveParam = slaves.getJSONObject(0);
			
			JSONObject slaveData = this.saveDetail(slaveParam);
			
			JSONArray slaveDatas = new JSONArray();
			slaveDatas.add(slaveData);
			data.put("slaves", slaveDatas);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			log.info("ParseException开始打印：");
			e.printStackTrace();
			log.info("e.getMessage()-->>"+e.getMessage());
			log.info("ParseException完成打印。");
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	@Override
	public JSONObject queryData(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}

	//新增子表
	@Override
	public JSONObject newDataDetail(JSONObject param) {
		return detailDao.create(param);
	}
	
	//查询子表
	@Override
	public JSONObject queryDataDetail(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = detailDao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	

	
}
